package com.pipi.jpa.controller;

import com.pipi.jpa.model.User;
import com.pipi.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by pipi on 2017/8/6.
 */
@Controller
@RequestMapping(path="/user")
public class UserController {

    @Autowired // This means to get the bean called userRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository userRepository;

    @GetMapping(path="/add") // Map ONLY GET Requests
    @ResponseBody
    public String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

//        User n = new User();
//        n.setName(name);
//        n.setEmail(email);
//        userRepository.save(n);
        for(int i=0;i<100;i++){
            User n = new User();
            n.setName("pipi" + i);
            n.setEmail(i+ "@qq.com");
            userRepository.save(n);
        }
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // This returns a JSON or XML with the users
        return userRepository.findAll();
    }
}
